package xyz.fefine;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by feng_ on 2016/9/2.
 * 语法树的主体,
 */
public class ASTList extends ASTree {

//    protected List<ASTree> children;

    protected ASTree[] children;
    int length = 0;

    public ASTList(List<ASTree> list) {

//        children = list;
        length = list.size();
        children =  (list.toArray(new ASTree[length]));

    }




    @Override
    public ASTree child(int i) {
        return children[i];
    }

    @Override
    public int numChildren() {
        return length;
    }

    @Override
    public Iterator<ASTree> children() {
        throw new StoneException("can't use iterator");
    }

    /**
     * 返回一个抽象语法树节点在程序内所处位置的字符串
     * @return
     */
    @Override
    public String location() {
        for (ASTree asTree : children) {
            String s = asTree.location();
            if (s != null) {
                return s;
            }
        }
        return null;
    }

    @Override
    public Object eval(Enviorment enviorment) {
//        throw new StoneException("cannot eval " + toString(),this);
        Object s = null;
        for (ASTree asTree : children) {
            s = asTree.eval(enviorment);
            System.out.println(asTree + "--->"+s);
        }
        return s;
    }

    @Override
    public void lookup(Symbols syms) {
        for (ASTree as : this.children) {
            as.lookup(syms);
        }
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        for (ASTree tree : children) {
            stringBuilder.append(" ");
            stringBuilder.append(tree.toString());
        }
        stringBuilder.append(")");
        return stringBuilder.toString();
    }
}
